<script setup lang="ts" name="role">
import { ref, watch, computed, reactive, nextTick, onMounted } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/common/composables/usePagination"
import { ElMessageBox, ElMessage } from 'element-plus'
import { listRole, delRole, changeRoleStatus } from '@/common/apis/system/role'
import UserDia from "./components/userDia.vue"
const { paginationData, handleSizeChange: originHandleSizeChange, handleCurrentChange: originHandleCurrentChange } = usePagination()
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh"
const searchData = ref({
  roleName: '',
  roleKey: '',
  status: '',
  create_time: []
})
defineOptions({
  // 命名当前组件
  name: "SystemRole"
})
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
const tableData = ref([])
const loading = ref(false)
const multipleSelection = ref([])
const searchFormRef = ref()
const dialogShow = ref(false)
// 添加一个标志，表示是否正在初始化数据
const isInitializing = ref(true)
// 搜索更多
const searchMore = ref(false)
// 搜索内容
const searchKey = ref('')
// 用于防止切换视图时的状态变化
const search = () => {
  getTableData()
}
// 重置
const resetSearch = () => {
  searchData.value = {
    roleName: '',
    roleKey: '',
    status: '',
    create_time: []
  }
  getTableData()
}
// 新增角色
const handleCreateTask = () => {
  dialogShow.value = true
}
// 批量删除
const handleMoreDelete = () => {
  const ids = multipleSelection.value.map((item: any) => item.id)
  const names = multipleSelection.value.map((item: any) => item.name)
  ElMessageBox.confirm(`确定要删除${names.join(',')}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delRole(ids).then((res: any) => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}
const getTableData = () => {
  isInitializing.value = true
  const params = {
    roleName: searchData.value.roleName,
    roleKey: searchData.value.roleKey,
    status: searchData.value.status,
    createTime: searchData.value.create_time[0],
    endTime: searchData.value.create_time[1],
    searchKey: searchKey.value,
    pageNum: 1,
    pageSize: 20
  }
  listRole(params).then((res: any) => {
    res.data.rows.forEach((item: any) => {
      item.status = item.status
    })
    tableData.value = res.data.rows
    paginationData.total = res.data.total

    // 数据加载完成后，将标志设置为 false
    setTimeout(() => {
      isInitializing.value = false
    }, 100)
  })
}
// 挂载
onMounted(() => {
  getTableData()
})
// 修改状态
const switchChange = (row: any) => {
  // 如果正在初始化，不执行任何操作
  if (isInitializing.value) return

  // 创建一个新对象，避免直接修改原始数据
  const data = {
    roleId: row.roleId,
    status: row.status
  }

  // 显示加载状态
  loading.value = true

  changeRoleStatus(data).then((res: any) => {
    ElMessage.success('状态修改成功')
  }).catch(e => {
    // 如果失败，恢复原来的状态值
    row.status = !row.status
    ElMessage.error('状态修改失败')
  }).finally(() => {
    loading.value = false
  })
}
// 获取行键
const getRowKeys = (row: any) => {
  return row.id
}
// 角色id
const id = ref('')
// 查看
const handleDetail = (roleId: any) => {
  id.value = roleId
  dialogShow.value = true
}
// 删除
const handleDelete = (id: any, name: any) => {
  ElMessageBox.confirm(`确定要删除${name}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delRole(id).then((res: any) => {
      // 刷新
      getTableData()
    })
  })
}
// 关闭弹窗
const dialogShowChange = (val: boolean) => {
  dialogShow.value = val
  id.value = ''
  getTableData()
}
useAutoRefresh(getTableData)
// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], () => {
  getTableData()
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="search">
          <template #append>
            <el-button :icon="Search" v-throttle="() => search()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item prop="roleName" label="角色名称">
            <el-input v-model="searchData.roleName" @change="search()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="roleKey" label="权限字符">
            <el-input v-model="searchData.roleKey" @change="search()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="status" label="角色状态">
            <el-select v-model="searchData.status" clearable placeholder="请选择" style="width: 240px" @change="search()">
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item prop="time_range" label="创建时间">
            <el-date-picker v-model="searchData.create_time" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="search()" />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask">新增角色</el-button>
          <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleMoreDelete">批量删除</el-button>
        </div>
      </div>
    </div>
    <div class="cpi-content-main">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table ref="tableRef" v-loading="loading" :data="tableData" :height="height" :width="width"
            :row-key="getRowKeys" show-overflow-tooltip>
            <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
            <el-table-column prop="roleName" label="角色名称" header-align="left" />
            <el-table-column prop="roleKey" label="权限字符" header-align="left" />
            <el-table-column prop="status" label="角色状态" header-align="left">
              <template #default="scope">
                <el-switch v-model="scope.row.status" v-if="!scope.row.admin"
                  @update:modelValue="(val: any) => switchChange(scope.row)" active-value="0" inactive-value="1"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" header-align="left" width="180" />
            <el-table-column fixed="right" label="操作" align="center" width="140">
              <template #default="scope">
                <el-space :size="12">
                  <el-link :underline="false" @click.stop="handleDetail(scope.row.roleId)" title="查看">
                    <el-icon :size="18" color="#409EFF">
                      <View />
                    </el-icon>
                  </el-link>
                  <el-link :underline="false" type="danger"
                    @click.stop="handleDelete(scope.row.roleId, scope.row.roleName)" title="删除">
                    <el-icon :size="18">
                      <Delete />
                    </el-icon>
                  </el-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-auto-resizer>
    </div>
    <div class="pager-wrapper">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :currentPage="paginationData.currentPage"
        @size-change="originHandleSizeChange" @current-change="originHandleCurrentChange" />
    </div>
    <UserDia :dialogShow="dialogShow" @update:dialogShow="dialogShowChange" :id="id" />
  </div>
</template>
<style lang="scss" scoped>
.csc-search-common-left {
  display: flex;
}

.csc-base-data {
  float: right;
}
</style>
